package com.basic.common.utils.smbUtils;

import jcifs.CIFSContext;
import jcifs.config.PropertyConfiguration;
import jcifs.context.BaseContext;
import jcifs.smb.NtlmPasswordAuthenticator;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

public class CifsContextPoolUtils {

    private static GenericObjectPool<CIFSContext> pool;

    public static void initPool(String username, String password) {
        GenericObjectPoolConfig<CIFSContext> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(100); // 最大连接数
        config.setMinIdle(10);   // 最小空闲连接数
        config.setMaxIdle(20);   // 最大空闲连接数
        config.setTestOnBorrow(true); // 获取连接时测试有效性

        pool = new GenericObjectPool<>(new CifsContextFactory(username, password), config);
    }

    public static CIFSContext borrowContext() throws Exception {
        return pool.borrowObject();
    }

    public static void returnContext(CIFSContext context) {
        pool.returnObject(context);
    }

    private static class CifsContextFactory extends BasePooledObjectFactory<CIFSContext> {

        private final String userName;
        private final String password;

        public CifsContextFactory(String userName, String password) {
            this.userName = userName;
            this.password = password;
        }

        @Override
        public CIFSContext create() throws Exception {
            return new BaseContext(new PropertyConfiguration(System.getProperties())).withCredentials(new NtlmPasswordAuthenticator("", userName, password));
        }

        @Override
        public void destroyObject(PooledObject<CIFSContext> p) throws Exception {
            // 如果有关闭方法，可以在这里调用
            p.getObject().close();
        }

        @Override
        public boolean validateObject(PooledObject<CIFSContext> p) {
            // 如果有验证方法，可以在这里调用
            return true;
        }

        @Override
        public PooledObject<CIFSContext> wrap(CIFSContext cifsContext) {
            return  new DefaultPooledObject<>(cifsContext);
        }

    }
}
